Most of this was pretty basic but I found practice the Set implementation helpful


In [1]:
class Set:
    '''Set has unique items and contains the add, remove,
    and contain methods'''
    
    def __init__(self, values=None):
        '''Gotta have dem constructors.
        Use this to define what happens on invocation.'''
        
        self.dict = {} # Remember Sets have unique items so keys in a dict are useful
        
        if values is not None: # If someone initialized with values
            for value in values: # Go through the values
                self.add(value) # Add them to the dict
                
    def __repr__(self):
        '''Define what this thing shows itself
        as when displayed in prompt or str()'''
        
        return "Set: " + str(self.dict.keys()) # Remember the dict is used for us to track unique keys
    
    def add(self, value):
        self.dict[value] = True # take the passed value and give it a key

    def contains(self, value):
        return value in self.dict # Handy that we have a dict eh?
    
    def remove(self, value):
        del self.dict[value] # ezpz remove keys

In [2]:
s = Set([1,2,3,4,5])

In [5]:
# Test __init__ and __repr__
s


Out[5]:
Set: [1, 2, 3, 4, 5]

In [6]:
s.add(6)

In [7]:
s.contains(6)


Out[7]:
True

In [8]:
s.contains(8)


Out[8]:
False

In [9]:
s.remove(3)

In [10]:
s.contains(3)


Out[10]:
False

Use partials


In [11]:
from functools import partial

In [14]:
# Normally I might define two functions and use one to execute the other
# Alternatively I could use partial

def exp(base, power):
    return base ** power

two_to_the = partial(exp,2)

In [15]:
two_to_the(3)


Out[15]:
8

Getting really functional


In [16]:
def double_dat(x):
    return 2* x

In [17]:
x = [1,2,3,4,5]

In [19]:
[double_dat(i) for i in x]


Out[19]:
[2, 4, 6, 8, 10]

In [21]:
map(double_dat, x) # cleaner


Out[21]:
[2, 4, 6, 8, 10]

In [25]:
list_doubler = partial(map, double_dat) # cheap vectorizer

In [26]:
list_doubler(x)


Out[26]:
[2, 4, 6, 8, 10]

In [27]:
# remember, filter is the if of a list comprehension

In [28]:
# reduce aggs together via the function rule as you iterate

In [29]:
# enumerate is the way to iterate with index

In [31]:
# zip is the shit, tuple together lists
# But is has a weird trick that lets you unpack by adding *

In [32]:
# args are arbitrary inputs without key specification
# kwargs are then keyed inputs

In [33]:
# Can use this to make your function input proof
# To "fix" inputs to f we can...
def doubler_correct(f):
    # f can be any kind of whacked out stuff
    def g(*args, **kwargs): # unpack into g
        return 2*f(*args, **kwargs) # pass through to f
    return g

In [ ]: